<template>
  <div class="find-facilities-container">
    <!-- 地图容器 -->
    <div ref="findFacilitiesMapView" class="find-facilities-map-view"></div>

    <!-- 操作说明悬浮按钮 -->
    <div class="instruction-button" @click="showInstructionPanel = true">
      <el-icon>
        <InfoFilled />
      </el-icon>
      <span>使用说明</span>
    </div>

    <!-- 操作说明面板 -->
    <el-drawer
      v-model="showInstructionPanel"
      direction="rtl"
      size="360px"
      :with-header="false"
      class="custom-drawer"
    >
      <div class="instruction-panel">
        <div class="drawer-header">
          <h2>校园设施导航使用说明</h2>
        </div>
        <div class="instruction-content">
          <h3>如何使用</h3>
          <ol>
            <li>点击地图选择您的当前位置</li>
            <li>使用左侧搜索栏查找您需要的设施</li>
            <li>点击列表中的设施可查看详细信息</li>
            <li>点击"导航到这里"按钮获取路线指引</li>
          </ol>
          <h3>图标说明</h3>
          <div class="icon-description">
            <div class="icon-item">
              <div class="icon-circle start"></div>
              <span>起点位置</span>
            </div>
            <div class="icon-item">
              <div class="icon-circle facility"></div>
              <span>设施位置</span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 设施搜索面板 -->
    <div class="search-panel">
      <div class="search-header">
        <h3>校园设施查找</h3>
      </div>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索设施名称或地址"
          clearable
          :prefix-icon="Search"
        />
      </div>
      <div class="filter-bar">
        <el-select v-model="filterType" placeholder="按类型筛选" clearable class="filter-select">
          <el-option
            v-for="type in facilityTypes"
            :key="type.value"
            :label="type.label"
            :value="type.value"
          />
        </el-select>
      </div>

      <!-- 设施列表 -->
      <div class="facility-list" v-loading="loading">
        <el-empty v-if="filteredFacilities.length === 0" description="未找到设施" />
        <div
          v-for="facility in filteredFacilities"
          :key="facility.OBJECTID"
          class="facility-item"
          @click="selectFacility(facility.OBJECTID)"
          :class="{ selected: selectedFacilityId === facility.OBJECTID }"
        >
          <div class="facility-name">{{ facility.Name || '未命名设施' }}</div>
          <div class="facility-address">{{ facility.address || '无地址信息' }}</div>
        </div>
      </div>
    </div>

    <!-- 设施信息区域 -->
    <el-drawer
      v-model="showFacilityInfo"
      direction="rtl"
      size="360px"
      :with-header="false"
      class="custom-drawer"
    >
      <div v-if="currentFacility && uiUpdateTrigger >= 0" class="facility-detail">
        <div class="facility-header">
          <h2>{{ currentFacility.Name || '设施详情' }}</h2>
          <el-button type="primary" size="small" @click="calculateRoute(currentFacility.OBJECTID)">
            <el-icon>
              <Location />
            </el-icon>
            导航到这里
          </el-button>
        </div>

        <el-descriptions :column="1" border>
          <el-descriptions-item label="设施类型">{{
            currentFacility.FacilityType || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{
            currentFacility.address || '未知'
          }}</el-descriptions-item>
          <el-descriptions-item v-if="currentFacility.distance" label="距离">
            {{ (currentFacility.distance / 1000).toFixed(2) }}公里
          </el-descriptions-item>
          <el-descriptions-item v-if="currentFacility.photo" label="设施照片">
            <div class="facility-photo">
              <img
                :src="currentFacility.photo"
                alt="设施照片"
                style="max-width: 100%; max-height: 200px"
              />
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 路线详情卡片 -->
    <div class="route-card" v-if="showRouteDetails">
      <div class="route-header">
        <h3>导航路线</h3>
        <el-button
          class="close-btn"
          type="info"
          circle
          size="small"
          @click="showRouteDetails = false"
        >
          <el-icon>
            <Close />
          </el-icon>
        </el-button>
      </div>

      <div class="route-summary">
        <div class="summary-item">
          <el-icon>
            <Position />
          </el-icon>
          <span>{{ (routeDistance / 1000).toFixed(2) }}km</span>
        </div>
        <div class="summary-item">
          <el-icon>
            <Timer />
          </el-icon>
          <span>约{{ Math.ceil(routeTime / 60) }}分钟</span>
        </div>
      </div>

      <el-collapse accordion>
        <el-collapse-item title="导航指引">
          <div class="step-info">
            <div class="step-title">{{ startLocationName }} → {{ destinationName }}</div>
            <div class="step-detail">
              <span>{{ (routeDistance / 1000).toFixed(2) }}km</span>
              <span>·</span>
              <span>{{ Math.ceil(routeTime / 60) }}分钟</span>
            </div>
          </div>
          <div class="instructions-list">
            <div
              v-for="(instruction, index) in routeInstructions"
              :key="index"
              class="instruction-item"
            >
              <span class="instruction-index">{{ index + 1 }}</span>
              <span class="instruction-text">{{ instruction }}</span>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>

      <div class="card-actions">
        <el-button type="danger" size="small" @click="clearRoute"> 清空路线 </el-button>
      </div>
    </div>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import {
  InfoFilled,
  Location,
  Position,
  Timer,
  Close,
  Delete,
  Search,
} from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import Polyline from '@arcgis/core/geometry/Polyline'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'
import SimpleLineSymbol from '@arcgis/core/symbols/SimpleLineSymbol'
import * as geometryEngine from '@arcgis/core/geometry/geometryEngine'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { ElMessage } from 'element-plus'
import { getGaoDeRoute, type Step } from '@/utils/gaodeAPI'
import Query from '@arcgis/core/rest/support/Query.js'

// 定义设施接口
interface Facility {
  OBJECTID: number
  Name: string
  FacilityType: string
  address: string
  photo?: string
  geometry?: {
    type: string
    longitude: number
    latitude: number
  }
  distance?: number
}

// 地图和视图
let map: __esri.Map
let view: __esri.MapView
const findFacilitiesMapView = ref<HTMLDivElement>()

// 设施图层
let facilityLayer: __esri.FeatureLayer | null = null

// 用户选择的位置
let userLocation: __esri.Point | null = null
let userLocationGraphic: __esri.Graphic | null = null

// 面板控制
const showInstructionPanel = ref(false)
const showFacilityInfo = ref(false)

// 设施数据
const facilities = ref<Facility[]>([])
const loading = ref(false)
const searchKeyword = ref('')
const filterType = ref('')
const selectedFacilityId = ref<number | null>(null)
let currentFacility: Facility | null = null
const uiUpdateTrigger = ref(0)

// 设施类型选项
const facilityTypes = [
  { value: '教室', label: '教室' },
  { value: '实验室', label: '实验室' },
  { value: '办公室', label: '办公室' },
  { value: '图书馆', label: '图书馆' },
  { value: '体育馆', label: '体育馆' },
  { value: '食堂', label: '食堂' },
  { value: '宿舍', label: '宿舍' },
  { value: '其他', label: '其他' },
]

// 筛选后的设施列表
const filteredFacilities = computed(() => {
  return facilities.value.filter((facility) => {
    const matchesKeyword =
      searchKeyword.value === '' ||
      facility.Name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      facility.address.toLowerCase().includes(searchKeyword.value.toLowerCase())

    const matchesType = filterType.value === '' || facility.FacilityType === filterType.value

    return matchesKeyword && matchesType
  })
})

// 路线规划
const showRouteDetails = ref(false)
const routeGraphics: __esri.Graphic[] = []
const routeDistance = ref(0)
const routeTime = ref(0)
const routeInstructions = ref<string[]>([])
const startLocationName = ref('您的位置')
const destinationName = ref('目的地')

// 导航状态
const isNavigating = ref(false)
const currentNavigationStep = ref('')
const nextNavigationStep = ref('')
const navigationProgress = ref(0)
const currentStepIndex = ref(0)

// 地图初始化
onMounted(async () => {
  await initMap()
  await loadFacilitiesLayer()
})

// 初始化地图
async function initMap() {
  map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  view = new MapView({
    container: findFacilitiesMapView.value!,
    map: map,
    center: [116.3, 39.9], // 默认中心点
    zoom: 10,
  })

  // 点击地图事件
  view.on('click', async (event) => {
    const hitResults = (await view?.hitTest(event))?.results as __esri.MapViewGraphicHit[]

    // 检查是否点击了设施
    const facilityFeature = hitResults.find(
      (result) => result.layer?.id === facilityLayer?.id,
    )?.graphic

    if (facilityFeature) {
      // 点击了设施
      const facility = {
        OBJECTID: facilityFeature.attributes.OBJECTID,
        Name: facilityFeature.attributes.Name || '未命名设施',
        FacilityType: facilityFeature.attributes.FacilityType || '其他',
        address: facilityFeature.attributes.address || '无地址信息',
        photo: facilityFeature.attributes.photo,
        geometry: {
          type: facilityFeature.geometry?.type,
          longitude: (facilityFeature.geometry as __esri.Point)?.longitude,
          latitude: (facilityFeature.geometry as __esri.Point)?.latitude,
        },
      }
      selectFacility(facility.OBJECTID)
    } else {
      // 点击了地图其他位置，设置为用户位置
      setUserLocation(event.mapPoint)
    }
  })
}

// 加载设施图层
async function loadFacilitiesLayer() {
  try {
    // 创建设施图层
    facilityLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/7XPW9RycLUzz2YAj/arcgis/rest/services/SchoolFacilityManagement/FeatureServer/0',
      outFields: ['*'],
      popupEnabled: false,
      renderer: {
        type: 'simple',
        symbol: {
          type: 'simple-marker',
          style: 'circle',
          size: 14,
          color: [0, 112, 255, 0.8],
          outline: {
            color: [255, 255, 255],
            width: 2,
          },
        },
      },
      // 添加标注
      labelingInfo: [
        {
          symbol: {
            type: 'text',
            color: '#333333',
            haloColor: '#ffffff',
            haloSize: 2,
            font: {
              size: 12,
              weight: 'normal',
            },
          },
          labelPlacement: 'above-center',
          labelExpressionInfo: {
            expression: '$feature.Name',
          },
          minScale: 5000,
          maxScale: 0,
        },
      ],
    })

    map.add(facilityLayer)

    // 加载设施列表
    loadFacilities()

    ElMessage.success('设施加载成功')
  } catch (error) {
    console.error('加载设施图层失败', error)
    ElMessage.error('加载设施图层失败')
  }
}

// 加载设施列表
const loadFacilities = async () => {
  if (!facilityLayer) return

  loading.value = true
  try {
    const query = new Query({
      where: '1=1', // 查询所有设施
      outFields: ['*'],
      returnGeometry: true,
    })

    const result = await facilityLayer.queryFeatures(query)

    facilities.value = result.features.map((feature) => {
      return {
        OBJECTID: feature.attributes.OBJECTID,
        Name: feature.attributes.Name || '未命名设施',
        FacilityType: feature.attributes.FacilityType || '其他',
        address: feature.attributes.address || '无地址信息',
        photo: feature.attributes.photo,
        geometry: {
          type: feature.geometry?.type!,
          longitude: (feature.geometry as __esri.Point)?.longitude!,
          latitude: (feature.geometry as __esri.Point)?.latitude!,
        },
      }
    })
  } catch (error) {
    console.error('加载设施列表失败:', error)
    ElMessage.error('加载设施列表失败')
  } finally {
    loading.value = false
  }
}

// 设置用户位置
function setUserLocation(point: __esri.Point) {
  // 清除之前的用户位置标记
  if (userLocationGraphic) {
    view.graphics.remove(userLocationGraphic)
  }

  // 保存用户位置
  userLocation = point

  // 创建用户位置标记
  const symbol = new SimpleMarkerSymbol({
    color: [255, 0, 0],
    size: 12,
    outline: {
      color: [255, 255, 255],
      width: 2,
    },
  })

  userLocationGraphic = new Graphic({
    geometry: point,
    symbol: symbol,
  })

  view.graphics.add(userLocationGraphic)

}


// 选择设施
function selectFacility(facilityID: number) {
  const facility = facilities.value.find((facility) => facility.OBJECTID === facilityID)!
  selectedFacilityId.value = facility.OBJECTID
  currentFacility = {
    OBJECTID: facility.OBJECTID,
    Name: facility.Name,
    FacilityType: facility.FacilityType,
    address: facility.address,
    photo: facility.photo,
    geometry: {
      type: facility.geometry?.type || '',
      longitude: facility.geometry?.longitude || 0,
      latitude: facility.geometry?.latitude || 0,
    },
    distance: facility.distance,
  }
  showFacilityInfo.value = true
  uiUpdateTrigger.value = Date.now() // 使用时间戳确保强制更新
  const point = new Point({
    longitude: facility.geometry?.longitude || 0,
    latitude: facility.geometry?.latitude || 0,
  })
  // 如果有地图视图，将地图中心移动到选中的设施位置
  if (view && facility.geometry) {
    view.goTo({
      target: point,
      zoom: 15,
    })
  }
}

// 计算路线
async function calculateRoute(facilityID: number) {
  if (!userLocation) {
    ElMessage.warning('请先选择您的位置')
    return
  }
  const facility = facilities.value.find((facility) => facility.OBJECTID === facilityID)!
  if (!facility.geometry) {
    ElMessage.warning('设施位置信息不完整')
    return
  }

  try {
    // 清除之前的路线
    clearRoute()

    // 保存目的地名称
    destinationName.value = facility.Name || '目的地'

    // 调用高德路径规划API
    const routeResult = await getGaoDeRoute(
      `${userLocation.longitude},${userLocation.latitude}`,
      `${facility.geometry.longitude},${facility.geometry.latitude}`,
    )

    // 绘制路线
    if (routeResult && routeResult.route && routeResult.route.paths[0]) {
      const path = routeResult.route.paths[0]

      // 将路径点转换为二维数组
      const pathPoints = path.steps.flatMap((step) => {
        return step.polyline.split(';').map((point) => {
          const [lng, lat] = point.split(',').map(Number)
          return [lng, lat]
        })
      })

      // 创建路线图形
      const routeLine = new Graphic({
        geometry: new Polyline({
          paths: [pathPoints],
        }),
        symbol: new SimpleLineSymbol({
          color: [0, 122, 194, 0.8],
          width: 4,
        }),
      })

      view.graphics.add(routeLine)
      routeGraphics.push(routeLine)

      // 提取路线指引信息
      routeInstructions.value = path.steps.map((step) => step.instruction)

      // 设置路线距离和时间
      routeDistance.value = Number(path.distance)
      routeTime.value = Number(path.duration)

      // 显示路线详情
      showRouteDetails.value = true

      ElMessage.success('路线规划成功')
    } else {
      ElMessage.warning('未找到合适的路线')
    }
  } catch (error) {
    console.error('路线规划失败', error)
    ElMessage.error('路线规划失败')
  }
}

// 清除路线
function clearRoute() {
  // 清除路线图形
  routeGraphics.forEach((graphic) => {
    view.graphics.remove(graphic)
  })
  routeGraphics.length = 0

  // 重置路线数据
  routeDistance.value = 0
  routeTime.value = 0
  routeInstructions.value = []
  showRouteDetails.value = false
  isNavigating.value = false
}

</script>

<style scoped>
.find-facilities-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.find-facilities-map-view {
  width: 100%;
  height: 100%;
}

.instruction-button {
  position: absolute;
  top: 20px;
  right: 20px;
  background-color: white;
  padding: 8px 12px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  cursor: pointer;
  z-index: 10;
}

.instruction-button span {
  margin-left: 5px;
}

.instruction-panel {
  padding: 20px;
}

.drawer-header {
  margin-bottom: 20px;
}

.instruction-content h3 {
  margin-top: 20px;
  margin-bottom: 10px;
}

.icon-description {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 10px;
}

.icon-item {
  display: flex;
  align-items: center;
}

.icon-circle {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 10px;
}

.icon-circle.start {
  background-color: red;
}

.icon-circle.facility {
  background-color: #0070c2;
}

.search-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 320px;
  max-height: calc(100vh - 40px);
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  z-index: 10;
  overflow: hidden;
}

.search-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.search-header h3 {
  margin: 0;
}

.search-bar {
  padding: 10px 15px;
}

.filter-bar {
  padding: 0 15px 10px;
}

.filter-select {
  width: 100%;
}

.facility-list {
  flex: 1;
  overflow-y: auto;
  max-height: calc(100vh - 200px);
  padding: 0 15px;
}

.facility-item {
  padding: 12px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.facility-item:hover {
  background-color: #f5f7fa;
}

.facility-item.selected {
  background-color: #ecf5ff;
}

.facility-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.facility-info {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 0.9em;
  margin-bottom: 5px;
}

.facility-address {
  color: #999;
  font-size: 0.85em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.distance {
  color: #409eff;
}

.facility-detail {
  padding: 20px;
}

.facility-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.facility-header h2 {
  margin: 0;
}

.route-card {
  position: absolute;
  bottom: 20px;
  right: 20px;
  width: 320px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 10;
  overflow: hidden;
  max-height: 70vh; /* 限制最大高度 */
  display: flex;
  flex-direction: column;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.route-header h3 {
  margin: 0;
}

.route-summary {
  display: flex;
  justify-content: space-around;
  padding: 15px;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eee;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.step-info {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.step-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.step-detail {
  color: #666;
  font-size: 0.9em;
  display: flex;
  gap: 5px;
}

.instructions-list {
  padding: 10px 15px;
  max-height: 40vh; /* 限制指引列表的最大高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}

.instruction-item {
  display: flex;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.instruction-index {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  background-color: #409eff;
  color: white;
  border-radius: 50%;
  margin-right: 10px;
  font-size: 0.8em;
  flex-shrink: 0; /* 防止缩小 */
}

.instruction-text {
  flex: 1;
  line-height: 1.5;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  border-top: 1px solid #eee;
}
.navigation-hint {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  max-width: 600px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
  padding: 15px;
  z-index: 20;
}

.hint-content {
  margin-bottom: 10px;
}

.current-instruction {
  font-size: 1.1em;
  font-weight: bold;
  margin-bottom: 8px;
}

.next-step {
  color: #666;
  font-size: 0.9em;
  display: flex;
  gap: 5px;
}

.custom-drawer :deep(.el-drawer__body) {
  padding: 0;
  overflow-y: auto;
}

@media (max-width: 768px) {
  .search-panel {
    width: 280px;
  }

  .route-card {
    width: 280px;
  }

  .navigation-hint {
    width: 90%;
  }
}
</style>
